package edu.calpoly.android.privatecontacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import android.annotation.TargetApi;
import android.app.ExpandableListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.SearchView.OnQueryTextListener;

public class MainActivity extends ExpandableListActivity {
	
    GroupsParseObjectAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
	private HashMap<String, List<ParseObject>> childObjectList;
    EditText searchBox;
    ImageButton searchButton;
    
    private Context mContext;
    private List<ParseObject> entries;
    private List<ParseObject> oStudents = new ArrayList<ParseObject>(0);
    private List<ParseObject> oTeachers= new ArrayList<ParseObject>(0);
    private List<ParseObject> oStaff= new ArrayList<ParseObject>(0);
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mContext = this;
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			setContentView(R.layout.contacts_list);
		} else {
			setContentView(R.layout.old_version_contacts_list);
			searchBox = (EditText) this.findViewById(R.id.search_box);
			searchBox.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
//					Log.d("ONKEY", "test is "+ s + ", demarcated by "+start+ ", "+before+", "+count);
//					Log.d("ONKEY", "text is "+ searchBox.getText().toString());
					showMatchingEntries(searchBox.getText().toString());
					expandCategories();
				}

			});
			searchButton = (ImageButton) this.findViewById(R.id.search_button);
		}

        // get the listview
        expListView = this.getExpandableListView();
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//				Log.d("ONCHILDCLICK", "parent is "+groupPosition+ ", child is " +childPosition+ ", id is "+id);
//				Log.d("ONCHILDCLICK", "CHILD is "+listDataChild.get( listDataHeader.get(groupPosition) ).get(childPosition) );
				ParseObject person = (ParseObject) listAdapter.getChild(groupPosition, childPosition);
				Intent intent;

				if(groupPosition == 0) {
					intent = new Intent(mContext, StudentActivity.class);
				   intent.putExtra("id", person.getObjectId());
				   intent.putExtra("table", "Student");
				}
				else if(groupPosition == 1) {
				   intent = new Intent(mContext, TeacherActivity.class);
				   intent.putExtra("id", person.getObjectId());
				   intent.putExtra("table", "Teacher");
				}
				else {
				   intent = new Intent(mContext, StaffActivity.class);
				   intent.putExtra("id", person.getObjectId());
				   intent.putExtra("table", "Staff");
				}
				
				startActivity(intent);
				
				return false;
			}
		});
 
        // preparing list data
        prepareListData();
        childObjectList = new HashMap<String, List<ParseObject>>();
        childObjectList.put(listDataHeader.get(0), oStudents);
        childObjectList.put(listDataHeader.get(1), oTeachers);
        childObjectList.put(listDataHeader.get(2), oStaff);

        new RemoteDataTask().execute("Student");
        new RemoteDataTask().execute("Teacher");
        new RemoteDataTask().execute("Staff");
 
//        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
        listAdapter = new GroupsParseObjectAdapter(this, listDataHeader, childObjectList);
 
        // setting list adapter
        expListView.setAdapter(listAdapter);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
			SearchView    searchView    = (SearchView)    menu.findItem(R.id.search).getActionView();
			searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		
			searchView.setOnQueryTextListener(new OnQueryTextListener() {
	
				@Override
				public boolean onQueryTextChange(String querytext) {
					Log.d("QUERYLISTENER", "query text is "+querytext+ ("null?"+querytext==null));
	//				if (querytext.length() > 1) {
						showMatchingEntries(querytext);
						expandCategories();
	//				}
					return true;
				}
	
				@Override
				public boolean onQueryTextSubmit(String querytext) {
					Log.d("QUERYLISTENER", "query submitted is "+querytext);
					return true;
				}
				
			});
		}
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
//	        case R.id.search:
//
//	        	Log.d("OPTIONSELECTED", "now calling onSearchRequested()");
//	        	onSearchRequested();
//	            return true;
	        default:
	            return false;
	    }
	}
	
	private void showMatchingEntries(String querytext) {
//		ExpandableListView lv = this.getExpandableListView();
//        listDataHeader = new ArrayList<String>();
		childObjectList.get("Student").clear();// = new HashMap<String, List<String>>();
		childObjectList.get("Teacher").clear();// = new HashMap<String, List<String>>();
		childObjectList.get("Staff").clear();// = new HashMap<String, List<String>>();
        
//        listDataHeader.add("Teachers");
        // I am having trouble with data types in this next block.
//        List<String> students = new ArrayList<String>();
		List<ParseObject> matchedStudents = new ArrayList<ParseObject>();
    	childObjectList.put("Student", matchedStudents);
        for (ParseObject student : oStudents) {

    		String fullname = student.getString("firstName") +" "+ student.getString("lastName");
        	fullname = fullname.toLowerCase();
        	
        	if (fullname.contains(querytext.toLowerCase())) {
        		matchedStudents.add(student);
        	} else {
        		Log.d("TAG", "no match "+fullname+ " and "+ querytext);
        	}
        }
        
		List<ParseObject> matchedTeachers = new ArrayList<ParseObject>();
    	childObjectList.put("Teacher", matchedTeachers);
        for (ParseObject teacher : oTeachers) {

    		String fullname = teacher.getString("firstName") +" "+ teacher.getString("lastName");
        	fullname = fullname.toLowerCase();
        	
        	if (fullname.contains(querytext.toLowerCase())) {
        		matchedTeachers.add(teacher);
        	} else {
        		Log.d("TAG", "no match "+fullname+ " and "+ querytext);
        	}
        }
        
		List<ParseObject> matchedStaff = new ArrayList<ParseObject>();
    	childObjectList.put("Staff", matchedStaff);
        for (ParseObject staff : oStaff) {

    		String fullname = staff.getString("firstName") +" "+ staff.getString("lastName");
        	fullname = fullname.toLowerCase();
        	
        	if (fullname.contains(querytext.toLowerCase())) {
        		matchedStaff.add(staff);
        	} else {
        		Log.d("TAG", "no match "+fullname+ " and "+ querytext);
        	}
        }

        this.listAdapter.notifyDataSetChanged();
	}
	
	private void expandCategories() {
		this.getExpandableListView().expandGroup(0);
		this.getExpandableListView().expandGroup(1);
		this.getExpandableListView().expandGroup(2);
	}
	
	private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();
        
        listDataHeader.add("Student");
        List<String> students = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.empty_list)) {
        	students.add(teacher);
        }
        listDataChild.put(listDataHeader.get(0), students);
        
        listDataHeader.add("Teacher");
        List<String> teachers = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.empty_list)) {
        	teachers.add(teacher);
        }
        listDataChild.put(listDataHeader.get(1), teachers);
        
        listDataHeader.add("Staff");
        List<String> staff = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.empty_list)) {
        	staff.add(teacher);
        }
        listDataChild.put(listDataHeader.get(2), staff);
	}
	
	@SuppressWarnings("unused")
	private void showDetailOf(int parentPosition, int childPositionq) {
		
	}
	
	private class RemoteDataTask extends AsyncTask<String, Void, Void> {
		// Override this method to do custom remote calls
		private String mHeader;
		
		protected Void doInBackground(String... header ) {
			this.mHeader=header[0];
			
			// Gets the current list of todos in sorted order
			ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(mHeader);
			query.orderByDescending("lastName");

			try {
				entries = query.find();
			} catch (ParseException e) {

			}
			return null;
		}

		@Override
		protected void onPreExecute() {
//			ListActivity.this.progressDialog = ProgressDialog.show(ListActivity.this, "", "Loading...", true);
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {

			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Void result) {
			// Put the list of todos into the list view
//			ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListDisplayActivity.this, R.layout.entry);
			if (mHeader.contentEquals("Student")) {
				oStudents = entries;
				childObjectList.put(listDataHeader.get(0), new ArrayList<ParseObject>(oStudents));
			} else if (mHeader.contentEquals("Teacher")) {
				oTeachers = entries;
				childObjectList.put(listDataHeader.get(1), new ArrayList<ParseObject>(oTeachers));
			} else {
				oStaff = entries;
				childObjectList.put(listDataHeader.get(2), new ArrayList<ParseObject>(oStaff));
			}
	        listDataChild.get(mHeader).clear();// = new HashMap<String, List<String>>();
			for (ParseObject entry : entries) {
				listDataChild.get(mHeader).add((String)entry.get("lastName"));
			}
			Log.d("NOTIFY", "notify Data Set Changed!");
//			listAdapter.notifyDataSetChanged();
//			setListAdapter(adapter);
//			//ListActivity.this.progressDialog.dismiss();
//			TextView empty = (TextView) findViewById(android.R.id.empty);
//			empty.setVisibility(View.VISIBLE);
		}
	}

}
